# -8- encoding:utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponse,Http404
from forms import StudioForm
from common.port import jsonpost
from ajax import get_globals
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from os import path
import os
import json
from models import Studio,TempModel,DeployAccount
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from common.db_tools import to_dict, form_to_head
from forms import ChoiceForm
from django.core.urlresolvers import reverse
from resource import LogoSaver,FaviconSaver
from freeze import Freeze
from tasks import update_studio_appset_with_celery
import base64


# Create your views here.

def display_list(request):
    return render(request,'studio/disp_list.html')



@csrf_exempt
@login_required(login_url='/admin/login/')
def add(request):
    if request.method=='GET':
        # pts=PTS()
        # studios= sorted( pts.get_studios() )
        
        # dc={
            # 'studios': studios
        # }
        dc={
            'form':ChoiceForm()
        }
        return render(request,'studio/add.html',context=dc)
    else:
        form = ChoiceForm(request.REQUEST)
        if form.is_valid():
            s=Studio.objects.create(name=form.cleaned_data.get('name'))
            update_studio_appset_with_celery.delay(s.name)
            return redirect(reverse('edit_studio',args=(s.pk,)))
        else:
            return render(request,'studio/add.html',context={'form':form})      
        # return jsonpost(request, get_globals())

@csrf_exempt
@login_required(login_url='/admin/login/')
def edit(request,studio_pk):
    if request.method=='GET':
        studio = Studio.objects.get(pk=studio_pk)
        temps= TempModel.objects.all()
        accounts = DeployAccount.objects.all()
        studio_dc = to_dict(studio)
        studio_dc['code_inject'] = base64.b64encode(studio_dc['code_inject'].encode('utf8'))
        return render(request,'studio/studio_edit.html',context={'studio':json.dumps(studio_dc),
                                                                 'heads':json.dumps(form_to_head(StudioForm())),
                                                                 'temps':json.dumps([to_dict(temp) for temp in temps]),
                                                                 'accounts':json.dumps([to_dict(account) for account in accounts]),
                                                                 'SITE_DOMAIN':settings.APG_DOMAIN,
                                                                 'channel':'studio'})
    else:
        return jsonpost(request, get_globals())    

@csrf_exempt
def upload(request,cat):
    file=request.FILES.get('file')
    studio=request.REQUEST.get('studio')
    if cat=='logo':
        logo=LogoSaver(file,studio)
    elif cat =='favicon':
        logo=FaviconSaver(file, studio)
    else:
        raise Http404('{path} is not right path'.format(path=request.path))
    
    if logo.is_valid():
        logo.save()
        return HttpResponse(json.dumps({'url':logo.get_url()}),content_type="application/json")
    else:
        return HttpResponse(json.dumps({'msg':logo.get_msg()}),content_type="application/json")


@login_required(login_url='/admin/login/')
def download(request,studio):
    s = Studio.objects.get(name=studio)
    html_dir= os.path.join(settings.MEDIA_ROOT,'html')
    ifile = os.path.join(html_dir,studio)+'.zip'
    with open(ifile,'rb') as f:
        rs = HttpResponse(f.read())
        rs['Content-type'] = 'application/octet-stream'  # 'text/plain'
        rs['Content-Disposition'] = 'attachment; filename="{name}.zip"'.format(name=studio)
        return rs



# from tasks import iadd
# def dotry(request):
    # add.delay(4, 4)
    # return HttpResponse('ok')